package com.wsc.springbootrabbitmq.Consumer;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * springboot RabbitMq consumer
 */
@Component
public class MyConsumer {

    /**
     * 建立一个 binding 如果配置中的 Q 或者 exc 不存在就会新创建一个
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "${queue-name}",durable = "true"),
            exchange = @Exchange(value = "${exchange-name}",durable = "true",
                    type = "${exchange-type}",ignoreDeclarationExceptions = "true"),
            key = "${routing-key}"
    ))

    /**
     * 接收消息方法
     * annotation @RabbitHandler 监听到的消息会路由到这个方法中
     */
    @RabbitHandler
    public void receive(Message message, Channel channel) throws IOException {
        System.err.println("-----------------------------------");
        System.err.println("消费端 Payload :"+message.getPayload());
        //消息 ACK
        Long deliveryTag = (Long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
        channel.basicAck(deliveryTag, false);
    }

    /**
     * 接收 User 类型的消息
     */
    @RabbitHandler
    public void userReceive(@Payload com.wsc.springbootrabbitmq.pojo.User user, Channel channel,
                            @Headers Map<String,Object> headers) throws IOException {
        System.err.println("-----------------------------------");
        System.err.println(" 消费端 User 类型 Payload :"+user.toString());
        Long deliveryTag =(Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        channel.basicAck(deliveryTag, false);
    }

}
